const DictionaryAPI = require('../../utils/dictionary-api');
const YoudaoAPI = require('../../utils/youdao-api');

Page({
  data: {
    word: '',
    isCollected: false,
    wordInfo: {
      word: '',
      phonetic: '',
      audioUrl: '',
      meanings: [],
      etymology: [],
      synonyms: [],
      antonyms: [],
      memoryTip: ''
    },
    loading: false
  },

  onLoad: function(options) {
    const word = options.word;
    const fromSearch = options.fromSearch;
    
    if (word) {
      this.setData({ word: word });
      
      // 如果是从搜索页面来的，优先使用全局数据
      if (fromSearch === 'true') {
        const app = getApp();
        const searchWordData = app.globalData.searchWordData;
        
        if (searchWordData && searchWordData.word === word) {
          this.setData({
            wordInfo: {
              word: searchWordData.word,
              phonetic: searchWordData.phonetic || '',
              audioUrl: searchWordData.audioUrl || '',
              meanings: searchWordData.meanings || [],
              etymology: searchWordData.etymology || [],
              synonyms: searchWordData.synonyms || [],
              antonyms: searchWordData.antonyms || [],
              memoryTip: searchWordData.memoryTip || this.generateMemoryTip(searchWordData.word),
              chineseTranslation: searchWordData.chineseTranslation,
              originalInput: searchWordData.originalInput,
              isFromChinese: searchWordData.isFromChinese
            }
          });
          
          // 检查收藏状态
          this.checkCollectionStatus(word);
          
          // 清除全局数据
          app.globalData.searchWordData = null;
          return;
        }
      }
      
      // 否则正常搜索
      this.searchWord(word);
    }
  },

  // 搜索单词
  searchWord: function(word) {
    this.setData({ loading: true });
    
    const dictionaryAPI = new DictionaryAPI();
    const youdaoAPI = new YoudaoAPI();

    // 使用Dictionary API获取基础信息
    dictionaryAPI.searchWord(word)
      .then(wordData => {
        console.log('Dictionary API获取到的数据:', wordData);
        
        // 翻译meanings为中文
        return youdaoAPI.translateMeanings(wordData.meanings).then(translatedMeanings => {
          console.log('翻译后的释义:', translatedMeanings);
          
          // 构建完整的wordInfo对象
          const completeWordInfo = {
            word: wordData.word,
            phonetic: wordData.phonetic,
            audioUrl: wordData.audioUrl,
            meanings: translatedMeanings,
            etymology: wordData.etymology,
            synonyms: wordData.synonyms,
            antonyms: wordData.antonyms,
            memoryTip: wordData.memoryTip || this.generateMemoryTip(wordData.word)
          };
          
          this.setData({
            word: word,
            wordInfo: completeWordInfo,
            loading: false
          });
          
          // 检查收藏状态
          this.checkCollectionStatus(word);
        });
      })
      .catch(error => {
        console.error('获取单词信息失败:', error);
        // 使用模拟数据作为降级方案
        const mockWordInfo = {
          word: word,
          phonetic: '/未知/',
          audioUrl: '',
          meanings: [{
            partOfSpeech: '',
            definition: '暂无释义',
            example: ''
          }],
          etymology: [],
          synonyms: [],
          antonyms: [],
          memoryTip: this.generateMemoryTip(word)
        };
        
        this.setData({
          word: word,
          wordInfo: mockWordInfo,
          loading: false
        });
        
        // 检查收藏状态
        this.checkCollectionStatus(word);
        
        wx.showToast({
          title: '获取单词信息失败',
          icon: 'none'
        });
      });
  },

  // 播放发音
  playPronunciation: function() {
    const audioUrl = this.data.wordInfo.audioUrl;
    
    if (audioUrl) {
      console.log('播放音频:', audioUrl);
      
      // 停止之前的音频播放
      if (this.audioContext) {
        this.audioContext.stop();
        this.audioContext.destroy();
      }
      
      // 创建新的音频播放器
      this.audioContext = wx.createInnerAudioContext();
      this.audioContext.src = audioUrl;
      this.audioContext.autoplay = false;
      
      this.audioContext.onPlay(() => {
        console.log('开始播放音频');
        wx.showToast({
          title: '正在播放',
          icon: 'none',
          duration: 1000
        });
      });
      
      this.audioContext.onEnded(() => {
        console.log('音频播放结束');
      });
      
      this.audioContext.onError((res) => {
        console.error('音频播放失败:', res);
        wx.showToast({
          title: '播放失败',
          icon: 'none'
        });
      });
      
      // 开始播放
      this.audioContext.play();
    } else {
      wx.showToast({
        title: '暂无发音音频',
        icon: 'none'
      });
    }
  },

  // 检查收藏状态
  checkCollectionStatus: function(word) {
    const collections = wx.getStorageSync('wordsCollection') || [];
    const isCollected = collections.some(item => {
      const itemWord = typeof item === 'string' ? item : item.word;
      return itemWord === word;
    });
    this.setData({
      isCollected: isCollected
    });
  },

  // 切换收藏状态
  toggleCollect: function() {
    const word = this.data.word;
    const wordInfo = this.data.wordInfo;
    let collections = wx.getStorageSync('wordsCollection') || [];
    
    if (this.data.isCollected) {
      // 取消收藏
      collections = collections.filter(item => {
        const itemWord = typeof item === 'string' ? item : item.word;
        return itemWord !== word;
      });
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      });
    } else {
      // 添加收藏，保存详细信息
      const wordEntry = {
        word: word,
        phonetic: wordInfo.phonetic,
        meaning: wordInfo.chineseTranslation || 
                 (wordInfo.meanings && wordInfo.meanings.length > 0 
                  ? wordInfo.meanings[0].definition 
                  : '暂无释义'),
        chineseTranslation: wordInfo.chineseTranslation,
        collectTime: this.formatTime(new Date())
      };
      collections.unshift(wordEntry); // 添加到开头
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    }
    
    wx.setStorageSync('wordsCollection', collections);
    this.setData({
      isCollected: !this.data.isCollected
    });
  },

  // 搜索相关词汇
  searchRelatedWord: function(e) {
    const word = e.currentTarget.dataset.word;
    wx.redirectTo({
      url: `/pages/word-detail/word-detail?word=${word}`
    });
  },

  // 加入学习列表（实际是收藏功能）
  addToStudyList: function() {
    this.toggleCollect();
  },

  // 分享单词
  shareWord: function() {
    const wordInfo = this.data.wordInfo;
    
    if (!wordInfo || !wordInfo.word) {
      wx.showToast({
        title: '单词信息不完整',
        icon: 'none'
      });
      return;
    }
    
    let shareWord = '';
    let shareMeaning = '';
    
    // 检查是否是从中文查询来的
    if (wordInfo.isFromChinese) {
      // 从中文查询：第一个输入框放英文，第二个输入框放中文
      shareWord = wordInfo.word; // 英文单词
      shareMeaning = wordInfo.originalInput || wordInfo.chineseTranslation || '暂无释义'; // 中文原文
    } else {
      // 从英文查询：第一个输入框放英文，第二个输入框放中文释义
      shareWord = wordInfo.word; // 英文单词
      if (wordInfo.meanings && wordInfo.meanings.length > 0) {
        shareMeaning = wordInfo.meanings[0].definition || '暂无释义';
      } else if (wordInfo.chineseTranslation) {
        shareMeaning = wordInfo.chineseTranslation;
      } else {
        shareMeaning = '暂无释义';
      }
    }
    
    // 先保存分享数据到全局
    const app = getApp();
    app.globalData.shareData = {
      shareType: 'word',
      word: shareWord,
      meaning: shareMeaning
    };
    
    // 跳转到study页面（tabBar页面需要使用switchTab）
    wx.switchTab({
      url: '/pages/study/study'
    });
  },

  // 反馈错误
  reportError: function() {
    wx.showModal({
      title: '反馈错误',
      content: '请描述您发现的问题，我们会尽快处理。',
      editable: true,
      placeholderText: '请输入问题描述...',
      success: (res) => {
        if (res.confirm && res.content) {
          wx.showToast({
            title: '反馈已提交',
            icon: 'success'
          });
        }
      }
    });
  },

  // 生成记忆技巧
  generateMemoryTip: function(word) {
    const tips = [
      `联想记忆：可以通过词根词缀来记忆 "${word}"`,
      `场景记忆：想象一个包含 "${word}" 的生动场景`,
      `重复练习：多次重复朗读和使用 "${word}"`,
      `造句记忆：用 "${word}" 造几个简单的句子`,
      `联系记忆：将 "${word}" 与你熟悉的事物联系起来`
    ];
    return tips[Math.floor(Math.random() * tips.length)];
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 添加单词到不熟单词本
  addToDifficultWords: function() {
    const word = this.data.word;
    const wordInfo = this.data.wordInfo;
    this.addToWordNotebook(word, wordInfo, 'difficultWords', '不熟单词');
  },

  // 添加单词到错题本
  addToWrongWords: function() {
    const word = this.data.word;
    const wordInfo = this.data.wordInfo;
    this.addToWordNotebook(word, wordInfo, 'wrongWords', '错题');
  },

  // 通用添加单词到单词本的方法
  addToWordNotebook: function(word, wordInfo, storageKey, notebookName) {
    let notebook = wx.getStorageSync(storageKey) || [];
    
    // 检查是否已存在
    const exists = notebook.some(item => {
      const itemWord = typeof item === 'string' ? item : item.word;
      return itemWord === word;
    });
    
    if (exists) {
      wx.showToast({
        title: `已在${notebookName}本中`,
        icon: 'none'
      });
      return;
    }
    
    // 添加新单词
    const wordEntry = {
      word: word,
      meaning: wordInfo.meanings && wordInfo.meanings.length > 0 
               ? wordInfo.meanings[0].definition 
               : '暂无释义',
      addTime: this.formatTime(new Date())
    };
    
    notebook.unshift(wordEntry); // 添加到开头
    wx.setStorageSync(storageKey, notebook);
    
    wx.showToast({
      title: `已添加到${notebookName}本`,
      icon: 'success'
    });
  },

  // 格式化时间
  formatTime: function(date) {
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${month}-${day}`;
  },

  // 页面卸载时清理音频资源
  onUnload: function() {
    if (this.audioContext) {
      this.audioContext.stop();
      this.audioContext.destroy();
      this.audioContext = null;
    }
  }
}); 